package day20170427.kaoshi;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import day20170425.homework.entity.StudentEntity;

public class StudentDaoImpl implements StudentDao {
	
	private SAXReader saxReader = new SAXReader();
	
	private Document document = null;
	
	@Override
	/**
	 * xml增加
	 * @param student	需要增加的对象
	 * @return
	 */
	public boolean add(Student student){
		try {
			document = saxReader.read(Common.FILE);
			Element root = document.getRootElement();
			Element studentElement = root.addElement("student");
			studentElement.setAttributeValue("id", student.getId());
			Element nameElement = studentElement.addElement("name");
			nameElement.setText(student.getName());
			Element ageElement = studentElement.addElement("age");
			ageElement.setText(String.valueOf(student.getId()));
			Common.writeXMLDocument(document);
			return true;
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * xml查询
	 * @return
	 */
	public List<Student> findAllStudent(){
		List<Student> list = new ArrayList<Student>();
		try {
			document = saxReader.read(Common.FILE);
			List<Node> newList = document.selectNodes("//student/name");
			Element root = document.getRootElement();
			List<Node> sex = root.selectNodes("//sex");
			List<Node> age = root.selectNodes("//age");
			List<Node> name = root.selectNodes("//name");
			for(int i=0;i<name.size();i++){
				Node node = name.get(i);
				Element parent = node.getParent();
				Student student = new Student();
				System.out.println(parent.attributeValue("id"));
				student.setId(parent.attributeValue("id"));
				student.setName(name.get(i).getText());
				student.setAge(Integer.parseInt(age.get(i).getText()));
				list.add(student);
			}
			Common.writeXMLDocument(document);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
